﻿using SuperX.SuperSocket.Socket.Transfer.Server;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.IO;
using System.Threading.Tasks;

namespace SuperX.SuperSocket.Socket.Transfer.Server.UpLoad.Command
{
    public class DoDownload : CommandBase<TransferSession, BinaryRequestInfo>
    {
        public override string Name => "DoDownload";

        public override void ExecuteCommand(TransferSession session, BinaryRequestInfo requestInfo)
        {
            ConsoleLogHelper.Debug(Name);
            try
            {
                FileInfo ServerConfigInfo = SerializeHelp.Deserialize<FileInfo>(requestInfo.Body);
                long CurrentPos = ServerConfigInfo.TransferPos + ServerConfigInfo.TransferedLength;
                long TransferedLength = ServerConfigInfo.TransferedLength;
                long TransferLength = ServerConfigInfo.TransferLength;
                session.FileTransferEngine.m_fileStream.Position = CurrentPos;
                session.FileTransferEngine.DownloadInfo = ServerConfigInfo;
                //session.FileTransferEngine.OnTransferStart();
                var readBuffer = new byte[ServerConfigInfo.PacketSize];
                while (TransferedLength < TransferLength)
                {
                    lock (session.FileTransferEngine.downloadLockobj)
                    {
                        if (session == null)
                            return;
                        //if (session.FileTransferEngine.DownloadStatusCodes[ServerConfigInfo.ProjectId] == 1)
                        //{
                        //    session.FileTransferEngine.DownloadStatusCodes[ServerConfigInfo.ProjectId] = 2;
                        //    session.FileTransferEngine.m_StopEvent.Set();
                        //    return;
                        //}
                        int length = session.FileTransferEngine.m_fileStream.Read(readBuffer, 0, ServerConfigInfo.PacketSize);
                        session.FileTransferEngine.SendData(UpLoadOP.DoData, readBuffer, 0, length);
                        TransferedLength += length;
                        session.FileTransferEngine.DownloadInfo.TransferedLength = TransferedLength;
                        session.FileTransferEngine.OnTransferStep(TransferLength, TransferedLength, length);
                    }
                }
                //session.FileTransferEngine.SendData(UpLoadOP.DoEnd, new byte[] { 1 }, 0, 1);

                Task.Factory.StartNew(() =>
                {
                    session.FileTransferEngine.m_EndEvent.WaitOne(5000);
                    session.FileTransferEngine.DoDownloadEnd();
                });
            }
            catch (Exception ex)
            {
                //Log.Error(ex.ToString());
                ConsoleLogHelper.Warn(ex.ToString());
                //error to do;
            }
        }
    }
}